package com.qumitech.visualnovel.service.voiceRoom.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSON;
import com.qumitech.visualnovel.component.config.Config;
import com.qumitech.visualnovel.component.util.HttpInvokeUtil;
import com.qumitech.visualnovel.model.common.BaseRsp;
import com.qumitech.visualnovel.model.dao.console.UserInfo;
import com.qumitech.visualnovel.model.common.UrlConstant;
import com.qumitech.visualnovel.pubdef.dto.voiceroom.VoiceRoomVoiceAuditConfigOperationDTO;
import com.qumitech.visualnovel.pubdef.dto.voiceroom.VoiceRoomVoiceAuditResultOperationDTO;
import com.qumitech.visualnovel.service.voiceRoom.VoiceRoomVoiceAuditService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.io.File;

@Service
public class VoiceRoomVoiceAuditServiceImpl implements VoiceRoomVoiceAuditService {
    private static final String VOICE_AUDIT_URL_PREFIX="/voiceroom/console/voice/audit/result";
    private static final String VOICE_AUDIT_CONFIG_URL_PREFIX="/voiceroom/console/voice/audit/config";
    @Override
    public BaseRsp listVoiceAuditResult(Long uid, Integer riskType, String riskLevel, String fromStartTime , String toStartTime,String states, Integer offset, Integer limit) {
        String url = UrlConstant.SERVER_URL + VOICE_AUDIT_URL_PREFIX;
        Map<String, Object> req = new HashMap<>();
        createListVoiceAuditResultRequestMap(req,uid,riskType,riskLevel,fromStartTime,toStartTime,states,offset,limit);
        String body = HttpInvokeUtil.httpGet(url, req);
        BaseRsp result = JSON.parseObject(body, BaseRsp.class);
        JSONObject jsonData = (JSONObject)result.getData();
        if (jsonData.containsKey("result")) {
            JSONArray items = jsonData.getJSONArray("result");
            for (int idx=0; idx<items.size(); ++idx) {
                JSONObject item = items.getJSONObject(idx);
                if (item.containsKey("audio_url")) {
                    item.put("audio_url", getAudioURL(item));
                }
            }
        }
        return result;
    }

    private String getAudioURL(JSONObject item) {
        if (!item.containsKey("start_time") || !item.containsKey("id")) {
            return item.getString("audio_url");
        }

        String startTime = item.getString("start_time");
        String[] timeArray = startTime.split(" ");
        if (timeArray.length == 0) {
            return item.getString("audio_url");
        }

        String audioDate = timeArray[0];
        String audioFile = String.format("%d.mp3", item.getInteger("id"));
        String filePath = String.format("%s/audio/%s/%s", Config.getProperty("app.download.excel"), audioDate, audioFile);
        String downloadUrl = String.format("%s/audio/%s/%s", Config.getProperty("app.download.url"), audioDate, audioFile);

        File file = new File(filePath);
        if(!file.exists()) {
            return item.getString("audio_url");
        }

        String newUrl = String.format("%s/audio/%s/%s", Config.getProperty("app.download.url"), audioDate, audioFile);
        return newUrl;
    }

    public void createListVoiceAuditResultRequestMap(Map<String, Object> req,Long uid, Integer riskType, String riskLevel, String fromStartTime, String toStartTime,String states, Integer offset, Integer limit) {
        //require的参数需要判断是否为null
        MapCheckAndInsert(req, "uid", uid);
        MapCheckAndInsert(req, "risk_type", riskType);
        MapCheckAndInsert(req, "risk_level", riskLevel);
        MapCheckAndInsert(req, "from_start_time", fromStartTime);
        MapCheckAndInsert(req, "to_start_time", toStartTime);
        MapCheckAndInsert(req, "offset", offset);
        MapCheckAndInsert(req, "limit", limit);
        //list直接传输过去会造成服务端报错，需要转化形式。
        MapCheckAndInsert(req,"states",states);

    }
    public void MapCheckAndInsert(Map<String, Object> req,String key,Object obj){
        if(obj == null)
            return;
        req.put(key,obj);
    }

    @Override
    public BaseRsp operateVoiceAuditResult(VoiceRoomVoiceAuditResultOperationDTO operationDTO) {
        operationDTO.setOperator(getOperatorName());
        String url = UrlConstant.SERVER_URL + VOICE_AUDIT_URL_PREFIX+"/operation";
        String body = HttpInvokeUtil.httpPostJson(url, JSON.toJSONString(operationDTO), UrlConstant.DefaultEncode,null);
        return  JSON.parseObject(body, BaseRsp.class);
    }

    private String getOperatorName() {
        Subject subject = SecurityUtils.getSubject();
        UserInfo activeUser = (UserInfo) subject.getPrincipal();
        return activeUser.getUsername();
    }

    @Override
    public BaseRsp listVoiceAuditConfig() {
        String url = UrlConstant.SERVER_URL + VOICE_AUDIT_CONFIG_URL_PREFIX;
        Map<String, Object> req = new HashMap<>();
        String body = HttpInvokeUtil.httpGet(url, req);
        return JSON.parseObject(body, BaseRsp.class);
    }

    @Override
    public BaseRsp saveVoiceAuditConfig(VoiceRoomVoiceAuditConfigOperationDTO operationDTO) {
        if (operationDTO.getType().equals("delete")) {
            String url = UrlConstant.SERVER_URL + VOICE_AUDIT_CONFIG_URL_PREFIX + "/" + operationDTO.getId().toString();
            Map<String, String> headMap = new HashMap<>();
            String body = HttpInvokeUtil.httpDelete(url, headMap);
            return JSON.parseObject(body, BaseRsp.class);
        }
        operationDTO.setOperator(getOperatorName());
        String url = UrlConstant.SERVER_URL + VOICE_AUDIT_CONFIG_URL_PREFIX;
        String body = HttpInvokeUtil.httpPostJson(url, JSON.toJSONString(operationDTO), UrlConstant.DefaultEncode,null);
        return JSON.parseObject(body, BaseRsp.class);
    }

}
